import React from 'react';
import '../Styles/earth.css'
import TargetData from '../Data/target.json'
class CesiumComponent extends React.Component {
  state = {
    showModal: false
  };
  componentDidMount() {
    Cesium.Ion.defaultAccessToken = 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJqdGkiOiI4MmNkOWNhZC1hZjc4LTRjNDgtYTU2MC00ZjRkM2Q3NjQ4OTAiLCJpZCI6NzcxNDksImlhdCI6MTY1NzI2MTE4OH0.eE5ucAk-WLVL6V_X6C7ykrhDqRvQtldJq6JsEao3MBI';
    window.viewer = new Cesium.Viewer('cesiumContainer', {
      imageryProvider: Cesium.createWorldImagery(),
      baseLayerPicker: false,
      geocoder: false,
      homeButton: false,
      sceneModePicker: false,
      timeline: false,
      navigationHelpButton: false,
      animation: false,
    });
    this.handleAddTarget()
    this.handleSearchPlace()
  }
  //  加载海量数据并做数据查询
  handleAddTarget() {
    const positions = [];
    const colors = [];
    // Number.NEGATIVE_INFINITY 是js中的特殊值，表示负无穷大的数值。它是 Number 类的一个静态属性
    let west = Number.POSITIVE_INFINITY;
    let south = Number.POSITIVE_INFINITY;
    let east = Number.NEGATIVE_INFINITY;
    let north = Number.NEGATIVE_INFINITY;
    for (let i = 0; i < TargetData.length; ++i) {
      const lon = TargetData[i].lon;
      const lat = TargetData[i].lat;
      west = Math.min(west, lon);
      south = Math.min(south, lat);
      east = Math.max(east, lon);
      north = Math.max(north, lat);

      const position = Cesium.Cartesian3.fromDegrees(
        lon,
        lat,
        Math.random() * 50000
      );
      positions.push(position);
      const color = new Cesium.Color(
        Math.random(),
        Math.random(),
        Math.random(),
        1.0
      );
      colors.push(color);

      //   // 飞到目标范围
      handleFlyToTarget(west, south, east, north)
      function handleFlyToTarget(west, south, east, north) {
        var rectangle = Cesium.Rectangle.fromDegrees(west, south, east, north);
        viewer.camera.flyTo({
          destination: rectangle,
          duration: 2  // 动画持续时间（以秒为单位）
        });
      }
    }

    // // 创建点集合
    const primitive = new Cesium.PointPrimitiveCollection();
    const primitiveList = []
    // // 创建点并设置颜色
    for (let i = 0; i < TargetData.length; ++i) {
      const primitiveElement = primitive.add({
        id: TargetData[i].target_id,
        position: positions[i],
        color: colors[i],
        pixelSize: 5,
      });
      primitiveList.push(primitiveElement)
    }
    // // 添加点集合到场景
    viewer.scene.primitives.add(primitive);

    // 数据查询
    var handler = new Cesium.ScreenSpaceEventHandler(viewer.scene.canvas);
    handler.setInputAction(function (click) {
    closeModal()

      var pickedObject = viewer.scene.pick(click.position);
      if (Cesium.defined(pickedObject) && primitiveList.indexOf(pickedObject.primitive) !== -1) {
        var pickedId = pickedObject.id
        var pickedPoint = getPointFromPrimitive(pickedId);
        showPopup(pickedPoint);
        openModal()
      }
    }, Cesium.ScreenSpaceEventType.LEFT_CLICK);

    // 获取点击的点
    function getPointFromPrimitive(primitiveId) {
      for (let i = 0; i < TargetData.length; i++) {
        if (TargetData[i].target_id === primitiveId) {
          return TargetData[i]
        }
      }
    }
    let _this = this
    // 显示弹窗
    function showPopup(point) {
      _this.setState({
        targetData: point
      });

    }
    function openModal() {
      _this.setState({
        showModal: true
      });
    };

    function closeModal() {
      _this.setState({
        showModal: false
      });
    };

  };

  // 搜索功能
  handleSearchPlace() {
    // 添加搜索地点功能
    new Cesium.Geocoder({
      container: 'cesiumSearchContainer',
      scene: viewer.scene,
    });
  }
  render() {
    const { showModal, targetData } = this.state;
    return (
      <div >
        <div id="cesiumSearchContainer"></div>
        <div id="cesiumContainer" style={{ width: '100%', height: '100%' }}></div>
        {showModal && (
          <div id="popup" >
            <ul>
              {Object.keys(targetData).map((key) => (
                <li key={key}>
                  <strong>{key}: </strong>
                  {targetData[key] || '暂无信息'}
                </li>
              ))}
            </ul>
          </div>
        )}
      </div>
    );
  }
}
export default CesiumComponent;

